<?php

namespace App\Models\Arts;

use App\Models\BaseModel;
use App\Utils\Common;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\Calculation\MathTrig\Random;

class UserModel extends BaseModel
{
    use HasFactory;

    protected     $table            = 'user';
    public        $timestamps       = false;
    protected int $is_status_search = 1;// 默认使用 status = 1 筛选
    protected int $is_delete_search = 1;// 默认使用 is_delete = 0 筛选

    /**
     * 默认查询字段
     *
     * @var array|string[]
     */
    public array $select = ['*'];

    public function searchAccountAttribute($query, $value, array $params): mixed
    {
        return $query->where('account', $value);
    }

    public function searchEmailAttribute($query, $value, array $params): mixed
    {
        return $query->where('email', $value);
    }

    public function searchMobileAttribute($query, $value, array $params): mixed
    {
        return $query->where('mobile', $value);
    }

    /**
     * 获取用户信息 根据手机号
     * @param string $mobile
     * @return array
     */
    public function getByMobile(string $mobile)
    {
        $this->is_status_search = 0;
        return $this->getDetail(params: ['mobile' => $mobile]);
    }

    /**
     * 获取用户信息 根据账号
     * @param string $mobile
     * @return array
     */
    public function getByAccount(string $mobile)
    {
        $this->is_status_search = 0;
        return $this->getDetail(params: ['account' => $mobile]);
    }

    /**
     * 账号登录
     * @param string $account
     * @param string $password
     * @return bool
     */
    public function login(string $account, string $password)
    {
        $field = Str::is('email',$account) ? 'email' : 'account';
        $this->is_status_search = 0;
        if (!$user = $this->getDetail(params: [$field => $account])){
            return $this->error('账号错误');
        }

        if (!Hash::check(md5($password), $user['password'])){
            return $this->error('密码错误');
        }

        if ($user['status'] != 1){
            return $this->error('账号被锁定，无法登录');
        }

        //直接登录会员
        return $this->success('登录成功', $user);
    }

    /**
     * 注册
     * @param string $account 账号
     * @param string $mobile 手机号
     * @param string $password 密码
     * @param string $email 邮件
     * @param array $extend 扩展字段
     * @return bool
     */
    public function register(string $account = '', string $mobile = '', string $password = '', string $email = '', array $extend = [])
    {
        $password = Hash::make(md5($password ?: Random::rand()));
        $params   = [
            'mobile'     => $mobile,
            'account'    => $account,
            'nickname'   => $extend['nickname'] ?? Common::getRandNickName(),
            'password'   => $password,
            'email'      => $email,
            'sex'        => $extend['sex'] ?? 0,
            'avatar'     => $extend['avatar'] ?? '',
            'birthday'   => $extend['birthday'] ?? '',
            'status'     => 1,
            'created_at' => time()
        ];

        //账号注册时需要开启事务,避免出现垃圾数据
        DB::beginTransaction();
        if (!$user_id = $this->query()->insertGetId($params)) {
            DB::rollBack();
            return $this->error('注册失败');
        }
        //注册钱包
        if (!UserWalletModel::query()->insert(['user_id' => $user_id])) {
            DB::rollBack();
            return $this->error('注册失败');
        }
        DB::commit();

        return $this->success('注册成功', array_merge($params, [
            'id' => $user_id
        ]));
    }

    /**
     * 更新登录时间
     * @param int $user_id
     * @return bool
     */
    public static function loginTime(int $user_id): bool
    {
        $data['last_login_time'] = time();
        return (bool)self::query()->where('id', $user_id)->update($data);
    }

    /**===========================   分割线   ==============================**/


    public static function getUserInfoByUserId(string $user_id)
    {
        return self::query()->select('*')->where('id', $user_id)->where('status', 1)->where('is_delete', 0)->first();
    }

    /**
     * 校验密码
     * @param string $phone
     * @param string $password
     * @return array
     */
    public static function checkPassword(string $phone, string $password)
    {
        $query = self::query();
        $query->where('phone', $phone);
        $query->where('is_delete', 0);
        $user = $query->first();

        $exists = true;
        // 校验用户 手机号 和 密码
        if (!$user || !Hash::check(md5($password), $user['password'])) {
            $exists = false;
        }

        return [$exists, $user];
    }

    /**
     * 校验账户
     * @param string $openid
     * @param string $phone
     * @return array
     */
    public function checkExists(string $openid = '', string $phone = ''): array
    {
        $query = self::query();

        !empty($openid) && $query->where('openid', $openid);
        !empty($phone) && $query->where('phone', $phone);

        $query->where('is_delete', 0);

        $exists  = $query->exists();
        $user_id = $query->value('id');

        return [$exists, $user_id];
    }


    /**
     * 创建账号
     * @param array $params
     * @return bool|int
     */
    public static function createAccount(array $params): bool|int
    {
        if (empty($params['phone'])) {
            return false;
        }

        if (!empty($params['password'])) {
            $params['password'] = Hash::make(md5($params['password']));
        }

        $params['head_img']   = '/statics/v1/images/head_img.png';
        $params['nickname']   = Common::getRandNickName();
        $params['status']     = 1;
        $params['created_at'] = time();

        // 创建账户
        $user_id = self::query()->insertGetId($params);
        if (!$user_id) {
            return false;
        }

        return $user_id;
    }

    /**
     * 更新
     * @param int $user_id
     * @param array $params
     * @return bool
     */
    public static function edit(int $user_id, array $params): bool
    {
        // 密码加密
        if (!empty($params['password'])) {
            $params['password'] = Hash::make(md5($params['password']));
        }
        $params['updated_at'] = time();
        $update               = self::query()->where('id', $user_id)->update($params);
        return (bool)$update;
    }
}
